﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json;
using StackExchange.Redis;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    public class Order_SaveController : UserController
    {
        public IExpressService _express { get; set; }
        public IPaymentService _payment { get; set; }
        public IUser_addr_bookService _user_addr_book { get; set; }
        public IArticle_goodsService _article_goods { get; set; }
        public IApp_cart_keysService _app_cart_keys { get; set; }
        public IArticleService _article { get; set; }
        public IUser_groupsService _user_groups { get; set; }
        public IOrdersService _orders { get; set; }
        public IUser_point_logService _user_point_log { get; set; }
        [Authorize]
        [HttpGet]
        public IActionResult Get(int address_id,int payment_id,int express_id,string accept_name, string province, string city, string area, string address, string mobile, string message,string post_code)
        {
            var userModel = GetUserInfo();
            if (userModel == null)
            {
                return Ok(new { status = 0, msg = "请先登录！" });
            }
            //获取传参信息===================================
            List<App_cart_keys> hideGoodsJson = null; //获取商品JSON数据
            string redisName = Request.Host.Host.ToLower().Replace(".", "_") + "_" + userModel.id + "_";
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"))
            {
                IDatabase db = redis.GetDatabase();
                string json = db.StringGet(redisName + "buy");
                if (!string.IsNullOrEmpty(json) && json != "[]")//不为空 开始反序列化
                {
                    hideGoodsJson = JsonConvert.DeserializeObject<List<App_cart_keys>>(json);
                }
            }

            int book_id = address_id;
            int is_invoice = 0; 
            string telphone = mobile;
            //检查传参信息===================================
            if (hideGoodsJson==null)
            {
                return Ok(new { status = 0, msg = "无法获取商品信息！" });
            }
            //检查商品是否同一家shop_id
            #region 检查商品是否同一家shop_id
            int supply = hideGoodsJson.Select(a => a.shop_id).Distinct().Count();
            if (supply > 1)
            {
                return Ok(new { status = 0, msg = "每个订单只能有同一家商品！" });
            } 
            #endregion
            if (express_id == 0)
            {
                return Ok(new { status = 0, msg = "请选择配送方式！" });
            }
            if (payment_id == 0)
            {
                return Ok(new { status = 0, msg = "请选择支付方式！" });
            }
            Express expModel = _express.GetModel(express_id);
            if (expModel == null)
            {
                return Ok(new { status = 0, msg = "配送方式不存在或已删除！" });
            }
            //检查支付方式
            Payment payModel = _payment.GetModel(payment_id);
            if (payModel == null)
            {
                return Ok(new { status = 0, msg = "支付方式不存在或已删除！" });
            }
            //检查收货人
            if (string.IsNullOrEmpty(accept_name))
            {
                return Ok(new { status = 0, msg = "请输入收货人姓名！" });
            }
            //检查手机和电话
            if (string.IsNullOrEmpty(telphone) && string.IsNullOrEmpty(mobile))
            {
                return Ok(new { status = 0, msg = "请输入收货人联系手机！" });
            }
            //检查地区
            if (string.IsNullOrEmpty(province) && string.IsNullOrEmpty(city))
            {
                return Ok(new { status = 0, msg = "请选择您所在的省市区！" });
            }
            //检查地址
            if (string.IsNullOrEmpty(address))
            {
                return Ok(new { status = 0, msg = "请输入详细的收货地址！" });
            }
                int user_id = userModel.id;
                int user_group_id = userModel.group_id;
                string user_name = userModel.user_name;
                //检查是否需要添加会员地址
                if (book_id == 0)
                {
                    User_addr_book addrModel = new User_addr_book();
                    addrModel.user_id = userModel.id;
                    addrModel.user_name = userModel.user_name;
                    addrModel.accept_name = accept_name;
                    addrModel.area = province + "," + city + "," + area;
                    addrModel.address = address;
                    addrModel.mobile = mobile;
                    addrModel.telphone = telphone;
                    addrModel.email = string.Empty;
                    addrModel.post_code = post_code;
                    _user_addr_book.Add(addrModel);
                }
            //获取商品信息==================================
            ShopCart.AppCartHelper shopcart = new ShopCart.AppCartHelper(_app_cart_keys, _article, _user_groups, _article_goods);
            List<cart_items> goodsList = shopcart.ToList(hideGoodsJson, user_group_id); //商品列表
            cart_total goodsTotal = shopcart.GetTotal(goodsList); //商品统计
            if (goodsList == null)
            {
                return Ok(new { status = 0, msg = "商品为空，无法结算！" });
            }
            //如果积分换购，检查一下用户积分是否足够扣减
            if (goodsTotal.total_point < 0 && userModel.point < (goodsTotal.total_point * -1))
            {
                return Ok(new { status = 0, msg = "您的账户积分不足，无法结算！" });
            }
            //保存订单=======================================
            Orders model = new Orders();
            model.shop_id = hideGoodsJson.Select(a => a.shop_id).FirstOrDefault();
            model.order_no = "B" + Utils.GetOrderNumber(); //订单号B开头为商品订单
            model.user_id = user_id;
            model.user_name = user_name;
            model.payment_id = payment_id;
            model.express_id = express_id;
            model.accept_name = accept_name;
            model.area = province + "," + city + "," + area; //省市区以逗号相隔
            model.address = address;
            model.telphone = telphone;
            model.mobile = mobile;
            model.message = message;
            model.email = string.Empty;
            model.post_code = post_code;
            model.is_invoice = is_invoice;
            model.payable_amount = goodsTotal.payable_amount;
            model.real_amount = goodsTotal.real_amount;
            model.pv_amount = goodsTotal.pv_amount;
            model.express_status = 1;
            model.express_fee = expModel.express_fee; //物流费用
                                                      //是否先款后货
            if (payModel.type == 1)
            {
                model.payment_status = 1; //标记未付款
                if (payModel.poundage_type == 1 && payModel.poundage_amount > 0) //百分比
                {
                    model.payment_fee = model.real_amount * payModel.poundage_amount / 100;
                }
                else //固定金额
                {
                    model.payment_fee = payModel.poundage_amount;
                }
            }
            ////是否开具发票
            //if (model.is_invoice == 1)
            //{
            //    model.invoice_title = invoice_title;
            //    if (orderConfig.taxtype == 1 && orderConfig.taxamount > 0) //百分比
            //    {
            //        model.invoice_taxes = model.real_amount * orderConfig.taxamount / 100;
            //    }
            //    else //固定金额
            //    {
            //        model.invoice_taxes = orderConfig.taxamount;
            //    }
            //}
            //订单总金额=实付商品金额+运费+支付手续费+税金
            model.order_amount = model.real_amount + model.express_fee + model.payment_fee + model.invoice_taxes;
            //购物积分,可为负数
            model.point = goodsTotal.total_point;
            model.add_time = DateTime.Now;
            //商品详细列表
            List<Order_goods> gls = new List<Order_goods>();
            foreach (cart_items item in goodsList)
            {
                //检查库存数量
                if (_article.GetStockQuantity(item.article_id, item.goods_id) < item.quantity)
                {
                    return Ok(new { status = 0, msg = "订单中某个商品库存不足，请修改重试！" });
                }
                //添加进订单列表
                gls.Add(new Order_goods
                {
                    shop_id = item.shop_id,
                    article_id = item.article_id,
                    goods_id = item.goods_id,
                    goods_no = item.goods_no,
                    goods_title = item.title,
                    img_url = item.img_url,
                    spec_text = item.spec_text,
                    goods_price = item.sell_price,
                    goods_pv_price = item.pv_price,
                    real_price = item.user_price,
                    real_pv_price = item.user_pv_price,
                    quantity = item.quantity,
                    point = item.point
                }); ;
            }
            model.order_goods = gls;
            int result = _orders.Add(model);
            if (result < 1)
            {
                return Ok(new { status = 0, msg = "订单保存发生错误！" });
            }
            //扣除积分
            if (model.point < 0)
            {
                _user_point_log.Add(model.user_id, model.user_name, model.point, "积分换购，订单号：" + model.order_no, false);
            }
            //删除购物车对应的商品
            shopcart.Clear(hideGoodsJson,user_id);
            //清空结账清单
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"))
            {
                IDatabase db = redis.GetDatabase();
                db.KeyDelete(redisName + "buy");                
            }
            return Ok(new { status=1,msg= "订单已成功提交",order_id=result });
        }
    }
}